package util

import (
	"github.com/spf13/viper"
	"go_server/zinx/zlog"
	"io"
	"math"
	"os"
	"path"
	"runtime"
	"slices"
)

var (
	ProjectConfigPath = path.Dir(getCurrentPath() + "/../") + "/conf/"
)

func getCurrentPath() string {
	_, filename, _, ok := runtime.Caller(0)
	if !ok {
		zlog.Fatal("get current filePath err!!!!")
	}
	return path.Dir(filename)
}

func CreateConfig(file string) (*viper.Viper, string) {
	config := viper.New()
	configPath := ProjectConfigPath
	config.AddConfigPath(configPath)
	config.SetConfigName(file)
	config.SetConfigType("yaml")
	configFile := configPath + file + ".yaml"

	if err := config.ReadInConfig(); err != nil {
		if _, ok := err.(viper.ConfigFileNotFoundError); ok {
			zlog.Panicf("找不到配置文件：%s", configFile)
		} else {
			zlog.Panicf("解析配置文件 %s 出错: %v", configFile, err)
		}
	}

	return config, configFile
}

func GetReadFileBuf(pathFileName string) []byte {
	fin, err := os.Open(pathFileName)
	if err != nil {
		zlog.Panicf("GetReadFileBuf err!!! filename: %s, err: %v", pathFileName, err)
	}
	defer fin.Close()

	const count = 6.0
	info, err := fin.Stat()
	if err != nil {
		zlog.Panicf("GetReadFileBuf err!!! filename: %s, err: %v", pathFileName, err)
	}
	size := info.Size()
	seg := int(math.Ceil(float64(size) / count))

	totalBuffer := make([]byte, 0, count)
	for {
		buffer := make([]byte, seg)
		n, err := fin.Read(buffer)
		if err != nil {
			if err != io.EOF {
				zlog.Panicf("GetReadFileBuf err!!! filename: %s, err: %v", pathFileName, err)
			} else {
				if len(buffer) > 0 {
					totalBuffer = slices.Concat(totalBuffer, buffer[:n])
				}
				break
			}
		}
		totalBuffer = slices.Concat(totalBuffer, buffer[:n])
	}

	if len(totalBuffer) <= 0 {
		zlog.Panicf("GetReadFileBuf err!!! filename: %s, err: %v", pathFileName, err)
	}

	return totalBuffer
}